package com.itxiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.dao.*;
import com.itxiao.entity.*;
import com.itxiao.pojo.bo.Page;
import com.itxiao.pojo.vo.PageResult;
import com.itxiao.pojo.vo.R;
import com.itxiao.service.SysUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2025-09-17 15:07:29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Resource
    private SysUserDao dao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysMenuDao sysMenuDao;
    @Resource
    private SysRoleMenuDao sysRoleMenuDao;
    @Resource
    private StringRedisTemplate template;

    @Override
    public R queryList(Page page) {
        // 1. 查询总记录数
        int total = dao.countByPage(page);
        // 2. 查询当前页数据
        List<SysUser> list = dao.queryListByPage(page);
        // 3. 封装分页结果
        PageResult<SysUser> result = new PageResult<>(list,total);
        return R.ok(result);
    }

    @Override
    @Transactional
    public R add(SysUser sysUser) {
        int insert = dao.insert(sysUser);
        if (insert  == 0) {
            return R.fail("插入失败");
        }
        SysUserRole sysUserRole = new SysUserRole(0,sysUser.getId(),sysUser.getRoleId());
        sysUserRoleDao.insert(sysUserRole);
        return R.ok();
    }

    @Override
    @Transactional
    public R updateInfo(SysUser sysUser) {
        int insert = dao.updateById(sysUser);
        if (insert  == 0) {
            return R.fail("修改失败");
        }
        Integer userId = sysUser.getId();
        sysUserRoleDao.deleteByUserId(userId);
        SysUserRole sysUserRole = new SysUserRole(0,userId,sysUser.getRoleId());
        sysUserRoleDao.insert(sysUserRole);
        return R.ok();
    }

    @Override
    public R del(List<Integer> ids) {
        return R.ok(dao.deleteBatchIds(ids));
    }

    @Override
    public R getUserInfo(String token) {
        SysUser sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                SysUser.class
        );
        if (sysUser == null) {
            return R.fail("登录失效");
        }
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(
                new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId())
        );
        if (sysUserRole == null) {
            return R.fail("登录失效");
        }
        SysRole sysRole = sysRoleDao.selectById(sysUserRole.getRoleId());
        if (sysRole == null) {
            return R.fail("角色不存在");
        }

        sysUser.setRoleId(sysRole.getId());
        sysUser.setRoleName(sysRole.getName());
        List<Integer> menuIds = sysRoleMenuDao.selectList(
                        new QueryWrapper<SysRoleMenu>().eq("role_id", sysUserRole.getRoleId())
                )
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toList());

        if (menuIds.isEmpty()) {
            return R.fail("该角色未分配菜单");
        }

        // 4. 查询菜单列表（包含权限标识 perms）
        List<SysMenu> menuList = sysMenuDao.selectList(
                new QueryWrapper<SysMenu>().in("id", menuIds)
        );

        if (menuList.isEmpty()) {
            return R.fail("该角色未分配菜单");
        }

        // ✅ 5. 组装 permissions：提取所有非空的 perms，去重
        List<String> permissions = menuList.stream()
                .map(SysMenu::getPerms)
                .filter(StringUtils::hasText)
                .distinct()
                .collect(Collectors.toList());

        // ✅ 6. 组装 user 对象（只保留需要的字段）
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", sysUser.getId());
        userInfo.put("nickname", sysUser.getNickname());
        userInfo.put("sex", sysUser.getSex());
        userInfo.put("email", sysUser.getEmail());
        userInfo.put("phone", sysUser.getPhone());
        userInfo.put("avatar", sysUser.getAvatar());
        userInfo.put("status", sysUser.getStatus());
        userInfo.put("roleId", sysUser.getRoleId());
        userInfo.put("roleName", sysUser.getRoleName());

        // ✅ 7. 组装最终 data
        Map<String, Object> data = new HashMap<>();
        data.put("permissions", permissions);
        data.put("user", userInfo);

        // ✅ 8. 返回成功结果（假设 R.ok(data) 表示 code=0）
        return R.ok(data);
    }

}

